/*
 * Merger.cc
 *
 *  Created on: Apr 3, 2012
 *      Author: victor
 */

#include "Merger.h"

Merger::Merger(IOCard* newIOCard) : Thread("Merger"){
	ioCard = newIOCard;
	for (int i = 0; i < 3; i++){
		buffers[i] =  new TripleBuffer(new CameraBuffer(), new CameraBuffer(), new CameraBuffer);
	}

	amountOfCameras = 0;
}

Merger::~Merger(){
	delete[] buffers;
	delete[] cameras;
}

void Merger::receiveImage(int n, byte data) {
	for (int i = 0; i < 3; i++) {
		if (cameras[i] == n) {
			if (CameraBuffer* tmpBuffer = dynamic_cast<CameraBuffer*>(buffers[i]->getFillBuffer())) {
				tmpBuffer->setBeeld(n, data);
			}
		}
	}
}

void Merger::checkInCamera(int cameraNumber){
	cameras[amountOfCameras] = cameraNumber;
	amountOfCameras++;
}


void Merger::sendImageToIOCard(TripleBuffer * buffer){
	if (CameraBuffer* tmpBuffer = dynamic_cast<CameraBuffer*>(buffer->getReadBuffer())){
		ioCard->receiveImageFromCamera((int)tmpBuffer->getCamera(), tmpBuffer->getBeeld());
	}
}

void Merger::run(){
	for (;;){
		sendImageToIOCard(buffers[0]);
		sendImageToIOCard(buffers[1]);
		sendImageToIOCard(buffers[2]);
	}
}
